const {User} = require("../database/index.js");
const uuid = require("node-uuid");
const {formatDate} = require("../untils/index.js");

const getMessage = async () => {
    const allUser = await User.findAll()
    let allMessage = []
    allUser.forEach(function (item) {
        if (item.message) allMessage = allMessage.concat(JSON.parse(item.message))
    })
    allMessage = allMessage.sort(function (a, b) {
        return Date.parse(a.time) - Date.parse(b.time)
    })
    let resultMessage = JSON.stringify(allMessage)
    return resultMessage
}

// 聊天群
const chatConnectionFn = async (wss, WebSocket, urlObj) => {
    let account = urlObj.account
    console.log(formatDate(new Date()) + '：' + `用户${account}已连接`)
    let resultMessage = await getMessage()
    wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(resultMessage)
        }
    })
}
const chatMessageFn = async (wss, WebSocket, urlObj, msg) => {
    let receive_msg = JSON.parse(msg)
    const hasUser = await User.findOne({
        where: {
            account: receive_msg.account
        }
    })
    let remoteMessage = hasUser.message ? JSON.parse(hasUser.message) : []
    receive_msg.src = hasUser.src || ''
    // 撤回和新建
    if (receive_msg.msg_id) {
        remoteMessage.forEach(item => {
            if (item.msg_id === receive_msg.msg_id) {
                item.message = '已撤回一条数据'
                item.msg_type = 'delete'
            }
        })
    } else {
        receive_msg.msg_id = uuid.v1()
        remoteMessage.push(receive_msg)
    }
    await User.update(
        { message: JSON.stringify(remoteMessage)},
        { where: { id: hasUser.id } }
    )
    let resultMessage = await getMessage()
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(resultMessage)
        }
    })
}
const chatCloseFn = async (wss, WebSocket, urlObj) => {
    let account = urlObj.account
    console.log(formatDate(new Date()) + '：' + `用户${account}已断开`)
}


let webSocketCfg = {
    // 聊天群
    chat: {
        connectionFn: chatConnectionFn,
        messageFn: chatMessageFn,
        closeFn: chatCloseFn
    }
}

module.exports = {
    webSocketCfg,
    getMessage
}